<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: Alipay.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\payment;

use Alipay\Alipaynotify;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use app\api\model\dao\OrderInfo;
use Think\Log;
use think\Validate;
use think\Cache;


class Alipay extends PageBase
{

    private $objOrderInfo;

    public function __construct()
    {
        parent::__construct();
        $this->objOrderInfo = new OrderInfo();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'order_id' => 'require',
        ];
        $msg = [
            'order_id.require' => '订单号必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {

        if (isset($param['paybefore'])) {
            $ret = $this->checkToken($param);
            if (false === $ret) {
                return $this->getRes(Error::ERR_NO_AUTH);
            }

            // 1、参数校验
            $ret = $this->checkParam($param);
            if ($ret) {
                return $this->getRes(Error::ERR_PARAM, $ret);
            }

            $this->payBefore($param);
        } else {
            $this->payNotify($param);
        }
    }

    public function payBefore($param)
    {
        require_once EXTEND_PATH . 'Alipay/AopClient.php';
        require_once EXTEND_PATH . 'Alipay/request/AlipayTradeAppPayRequest.php';

        $alipay_config = config('alipay_config');

        $order_id = $param['order_id'];

        $out_trade_no = $order_id;
        $total_fee = 0;   //付款金额

        $order = $this->objOrderInfo->getOrderInfo($order_id);
        $order_amount = $order['order_amount'];
        $shipping_fee = $order['shipping_fee'];
        $total_fee = $order_amount + $shipping_fee;


        $aop = new \AopClient;
        $aop->gatewayUrl = $alipay_config['gateway_url'];
        $aop->appId = $alipay_config['app_id'];
        $aop->rsaPrivateKey = $alipay_config['private_key'];
        $aop->format = $alipay_config['format'];
        $aop->charset = $alipay_config['charset'];
        $aop->signType = $alipay_config['sign_type'];
        $aop->alipayrsaPublicKey = $alipay_config['alipay_public_key'];
        $request = new \AlipayTradeAppPayRequest();

        $biz_arr = [];
        $biz_arr['body'] = '测试';
        $biz_arr['subject'] = '温社支付测试';
        $biz_arr['out_trade_no'] = '' . $out_trade_no;
        $biz_arr['timeout_express'] = '30m';
        $biz_arr['total_amount'] = '' . $total_fee;
        $biz_arr['total_amount'] = '0.01';
        $biz_arr['product_code'] = 'QUICK_MSECURITY_PAY';

        $bizcontent = json_encode($biz_arr);

        $request->setNotifyUrl($alipay_config['notify_url']);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request);
        echo $response;
        exit;
    }

    public function payNotify($param)
    {
        require_once EXTEND_PATH . 'Alipay/AopClient.php';
        require_once EXTEND_PATH . 'Alipay/request/AlipayTradeAppPayRequest.php';

        $alipay_config = config('alipay_config');
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $alipay_config['alipay_public_key'];
        $flag = $aop->rsaCheckV1($_POST, NULL, $alipay_config['sign_type']);
        Log::log("payNotify:" . json_encode($param) . " return:" . json_encode($flag));
        if ($flag) {
            if (!empty($param['out_trade_no'])) {

                //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
                //商户订单号
                $out_trade_no = $param['out_trade_no'];

                //支付宝交易号
                $trade_no = $param['trade_no'];

                if ($param['trade_status'] == 'TRADE_FINISHED') {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                } else if ($param['trade_status'] == 'TRADE_SUCCESS') {
                    //更新支付状态和支付时间
                    $param = array(
                        'order_id' => $out_trade_no,
                        'order_status' => Flag::ORDER_STATUS_NOT_SENDING,
                        'pay_time' => time(),
                    );
                    $this->objOrderInfo->updateOrder($param);
                }
                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
                echo "success";        //请不要修改或删除
            } else { //验证签名失败
                echo "sign fail";
            }
        } else { //验证是否来自支付宝的通知失败
            echo "response fail";
        }
    }

}
